import { Tree } from '@alifd/next';
import React, { Children, useEffect, useState } from 'react'
import * as api from './api';
import { TreeProps } from '@alifd/next/types/tree';
import { flatToTree } from '@/utils/util';
import { t } from '@lingui/macro';

const TreeNode = Tree.Node;

interface RegionProps extends TreeProps {
  maxLevel?: number; // 最大层级，默认2，如果为1则只能选择城市
  onRegion?: (data: any) => void;
  type?: number; // 区分巴士和包车  1: 包车 2:平台巴士 3: 第三方巴士 4: 专线
}

/**
 * 通用行政区域选择
 * @returns
 */
const RegionTree = ({ type = 1, maxLevel = 2, onRegion, ...props }: RegionProps) => {

  const [data, setData] = useState<Array<any>>([]);
  const [selected, setSelected] = useState<string>('root');

  useEffect(() => {
    (async () => {
      const dataSource = await getData()
      setData(dataSource);
    })();
  }, []);

  async function getData() {
    const getScCityNode = async (city: any) => {
      const region = await api.getPricesScArea({ cityId: city.fullId });
      return {
        ...city,
        name: city.name,
        fullId: city.fullId,
        children: region.filter((p) => Object.keys(p).length !== 0).map((j: { result: any }) => ({
          ...j,
          name: j.result,
          fullId: `${city.name}:${j.result}`,
        })),
      };
    };

    const getBusCityNode = async (city: any) => {
      const region = await api.getPricesBusArea({ cityId: city.city });
      return {
        ...city,
        name: city.cityText,
        fullId: city.city,
        children: region.map((j: { result: any }) => ({
          ...j,
          name: j.result,
          fullId: `${city.cityText}:${j.result}`,
        })),
      };
    };

    const getRegionNode = async (p: { result: any }) => {
      const children = await api.allBusRegions({ companyId: '', type: 1, cityName: p.result });
      return {
        ...p,
        name: p.result,
        fullId: p.result,
        children: children.map((j: { result: any }) => ({
          ...j,
          name: j.result,
          fullId: `${p.result}:${j.result}`,
        })),
      };
    };

    let dataSource: Array<any> = [];

    switch (type) {
      case 1:
        const regions = await api.allRegions(maxLevel);
        dataSource = flatToTree(regions);
        break;

      case 2:
        const cities = await api.getStationsCity();
        dataSource = await Promise.all(cities.map(getBusCityNode));
        break;

      case 3:
        const busRegions = await api.allBusRegions({ companyId: '', type: 0 });
        dataSource = await Promise.all(busRegions.map(getRegionNode));
        break;

      case 4:
        const scCities = await api.getPricesScCity();
        dataSource = await Promise.all(scCities.map(getScCityNode));
        break;

      default:
        dataSource = [];
        break;
    }

    // 添加过滤条件  如果层级为1时则只能选择城市
    const filterByMaxLevel = (nodes: any[], level: number): any[] => {
      return nodes.map((node) => {
        if (level >= maxLevel) {
          delete node.children;
        } else if (node.children) {
          node.children = filterByMaxLevel(node.children, level + 1);
        }
        return node;
      }).filter((node) => Object.keys(node).length !== 0);
    };

    dataSource = filterByMaxLevel(dataSource, 1);

    return dataSource;
  }

  const handleSelected = (keys: string[], extra: any) => {
    if (!keys.length) return;
    setSelected(keys[0]);
    onRegion?.(extra.node.props.data);
  };

  function getIcon(level) {
    switch (level) {
      case 1:
        return <i className="iconfont icon-city" />;
      case 2:
        return <i className="iconfont icon-flag" />;
      default:
        return <i className="iconfont icon-location" />;
    }
  }


  function renderNode(item: any) {
    const isLeaf = !item.children?.length;
    const level = item.fullId?.split(':').length;
    return (
      <TreeNode
        key={item.fullId}
        label={item.name}
        icon={getIcon(level)}
        title={item.name}
        isLeaf={isLeaf}
        data={item}
      >
        {item.children?.map((c: any) => renderNode(c))}
      </TreeNode>
    );
  }

  return (
    <>
      <div>

      </div>
      <Tree
        isNodeBlock={{ indent: 10 }}
        style={{ width: '100%' }}
        selectedKeys={selected ? [selected] : []}
        onSelect={handleSelected}
        defaultExpandedKeys={['root']}
        {...props}
      >
        <TreeNode
          key="root"
          label={t`所有区域`}
          isLeaf={false}
        >
          {data?.map((item: any) => renderNode(item))}
        </TreeNode>
      </Tree>
    </>
  )
}

export default RegionTree
